package com.chapter1;

import java.util.HashMap;

/**
 * 简单工厂模式
 */
public class OperationTest {
    public static void main(String[] args) throws Exception {
        String operate = "/";
        Operation oper = OperationFactory.createOperate(operate); //作为工具类使用，不用单独创建对象才能调用方法
        oper.setNumberA(10);
        oper.setNumberB(0);
        double result = oper.getResult();
        System.out.println(result);
        Thread t1 = new Thread();


    }
}
abstract class Operation {
    private double numberA;
    private double numberB;

    public double getNumberA() {
        return numberA;
    }

    public void setNumberA(double numberA) {
        this.numberA = numberA;
    }

    public double getNumberB() {
        return numberB;
    }

    public void setNumberB(double numberB) {
        this.numberB = numberB;
    }

    public abstract double getResult() throws Exception;
}

class OperationAdd extends Operation{
    @Override
    public double getResult() {
        return super.getNumberA() + super.getNumberB();
    }
}

class OperationSub extends Operation{

    @Override
    public double getResult() {
        return super.getNumberA() - super.getNumberB();
    }
}

class OperationMul extends Operation{

    @Override
    public double getResult() {
        return super.getNumberA() * super.getNumberB();
    }
}

class OperationDiv extends Operation{

    @Override
    public double getResult() throws Exception {
        if(super.getNumberB() == 0){
            throw new Exception("除数不能为0！");
        }
        return  super.getNumberA() / super.getNumberB();
    }
}

class OperationFactory{
    //静态方法，类似于静态变量，静态方法也属于类，不属于实例的。
    // 静态方法只能访问类的静态变量，或调用类的静态方法。通常静态方法作为工具方法，被其它类使用，而不需要创建类的实例。
    // 譬如集合类、Wrapper类(String, Integer等)和工具类(java.util中的类)都有很多静态方法。通常java程序的开始就是一个main()方法，它就是个静态方法。
    public static Operation createOperate(String operate){
        if(operate.length() > 1){
            throw new RuntimeException("输入的符号不正确！");
        }
        Operation oper = null;
        switch (operate){
            case "+":
                oper = new OperationAdd();
                break;
            case "-":
                oper = new OperationSub();
                break;
            case "*":
                oper = new OperationMul();
                break;
            case "/":
                oper = new OperationDiv();
                break;
        }
        return oper;
    }
}